/*
*
* 登录模块 sign_in
* 切换城市 change_city
*
* */

;(function ($, window, document) {

    var setCookie = utilsLoad.setCookie,
        getCookie = utilsLoad.getCookie,
        getQueryString = utilsLoad.getQueryString,
        validatePhone = utilsLoad.validatePhone,
        validateEmail = utilsLoad.validateEmail,
        throttle = utilsLoad.throttle,
        createScript = utilsLoad.createScript,
        countDown = utilsLoad.countDown;

    // 第三方js，在线获取当前城市位置
    function loadLocation (callback){

        // 根据ip获取当前城市
        if(!("setCurrentLocation" in window)){
            window.setCurrentLocation = function (data){
                var ipCity = (data && data.city) || '',
                    cookieCity = getCookie('CURRENT_CITY');
                // 若已设置城市，则直接取cookie，否则根据ip获取当前城市
                if(!cookieCity){
                    setCookie('CURRENT_CITY', ipCity, 30);
                    cookieCity = ipCity
                }
                callback && callback(cookieCity, data)
            }
        }

        createScript({
            src: 'http://whois.pconline.com.cn/ipJson.jsp?callback=setCurrentLocation'
        })
    }

    // 获取地理位置，发送给后端
    loadLocation(function (city, location){

        $('.locationWrap').removeClass('hidden');
        $('.currentCity')
            .attr('title', city)
            .html((city.indexOf('市') >= 0 ? city.slice(0, -1) : city) || '--');

        location = location || {};

        // 进入首页，发送给后端，已登录用户的位置信息、ip地址
        if(window.location.pathname === '/' && getCookie('USER_TOKEN')){
            $.ajax({
                method: 'post',
                url: API_BASE_URL + '/management/addLoginLog',
                contentType: 'application/json',
                data: JSON.stringify({
                    loginIp: location.ip,
                    loginPosition: location.addr
                })
            })
        }
    });


    // 存储位置信息，默认为null
    var locationConfig = {
        china: null,
        abroad: null
    };

    // 定义 main 对象
    var thisObj = {
        // init
        init: function (){

            // 首页、职位首页 加载位置信息
            var pathname = window.location.pathname;
            if(pathname === '/' ||
               pathname === '/post' ||
               pathname === '/post/'){
                this.initLocationConfig()
            }

            var scrollTop = $(document).scrollTop(),
                $backTop = $('.backTop'),
                $searchContainer = $('.searchContainer');

            if(scrollTop > 150){
                $backTop.removeClass('hidden');
            }
            if(scrollTop > 290){
                $searchContainer.addClass('fixed')
            }

            // 滚动事件
            $(window).scroll(throttle(function () {
                scrollTop = $(document).scrollTop();
                // 显示/隐藏 "返回顶部"
                scrollTop > 150
                    ? $backTop.removeClass('hidden')
                    : $backTop.addClass('hidden');
                // fixed 搜索栏
                scrollTop > 290
                    ? $searchContainer.addClass('fixed')
                    : $searchContainer.removeClass('fixed')
            }, 300));

            // 返回顶部
            $backTop.click(function () {
                $('html,body').animate({
                    scrollTop: 0
                }, 'fast')
            })

        },
        // 获取所有位置信息
        initLocationConfig: function (){

            // 获取中国：省、市、区
            $reAjax({
                url: API_BASE_URL + '/sysNationControler/selectChinaAll'
            }, function (res) {
                res = res.responseJSON;
                if(res.message === 'success'){
                    locationConfig.china = res.data;
                    locationConfig.china.push({
                        code: 'other',
                        name: '国外'
                    })
                }else{
                    locationConfig.china = []
                }
            });
            // 获取国外：洲、国家
            $reAjax({
                url: API_BASE_URL + '/sysNationControler/selectAllRemoveChina'
            }, function (res) {
                res = res.responseJSON;
                if(res.message === 'success'){
                    locationConfig.abroad = res.data;
                    locationConfig.abroad.push({
                        code: 'china',
                        name: '国内'
                    })
                }else{
                    locationConfig.abroad = []
                }
            })
        },
        // 获取验证码
        get_validateCode: function (config){

            $.ajax({
                url: API_SIGN_URL + '/auth/code/getValidateCode',
                data: {
                    account: config.account
                },
                beforeSend() {
                    countDown(config.elem)
                }
            }).done(function (res) {
                if(res.message === 'success'){
                    layer.msg('验证码已发送');
                    setCookie('PHONE_CODE', res.data, 0.01)
                }else{
                    layer.alert(res.message, {
                        title: '操作提示',
                        time: 3000,
                        btn: ['关闭'],
                        shadeClose: true,
                        icon: 2
                    })
                }
            })
        },
        // 获取用户基本信息
        sign_getUser: function (token){

            $.ajax({
                url: API_SIGN_URL + '/rm/userExtension/findResumeByUserId',
                headers: {
                    "Authorization": "bearer " + token
                }
            }).done(function (res) {
                if(res.message === 'success'){
                    res = res.data;
                    var USER_BASE = res.userCode + ','
                        + res.nickName + ','
                        + res.picturePath;
                    setCookie('USER_BASE', USER_BASE, 1);
                }
            })
        },
        // 密码登录
        sign_pwd: function (data){

            $reAjax({
                method: 'post',
                url: API_SIGN_URL + '/auth/oauth/token',
                contentType: 'form',
                withCredentials: true,
                data: {
                    client_id: '1',
                    client_secret: 'server',
                    grant_type: 'password',
                    username: data.account,
                    password: data.password
                }
            }, function (res) {
                res = res.responseJSON;
                if(res.access_token){

                    layer.msg('登录成功');
                    setCookie('USER_TOKEN', res.access_token, 0.5);

                    thisObj.sign_getUser(res.access_token);
                    // 登录成功后，重定向
                    setTimeout(function () {
                        var redirect = getQueryString('redirect');
                        if(redirect){
                            window.location.href = decodeURIComponent(redirect)
                        }else {
                            window.location.reload()
                        }
                    }, 500)
                }else{
                    layer.alert(res.error, {
                        title: '操作提示',
                        time: 3000,
                        btn: ['关闭'],
                        shadeClose: true,
                        icon: 2
                    })
                }
                $(data.elem).removeAttr('disabled')
            }, function () {
                $(data.elem).attr('disabled', true)
            })
        },
        // 手机验证码登录
        sign_code: function (data){

            $reAjax({
                method: 'post',
                url: API_SIGN_URL + '/auth/oauth/token',
                contentType: 'form',
                withCredentials: true,
                data: {
                    client_id: '1',
                    client_secret: 'server',
                    grant_type: 'password',
                    auth_type: 'sms',
                    sms_token: getCookie('PHONE_CODE') || '',
                    source_from: 'zhaopin',
                    username: data.account,
                    password: data.password
                }
            }, function (res) {
                res = res.responseJSON;
                if(res.access_token){

                    layer.msg('登录成功');
                    setCookie('USER_TOKEN', res.access_token, 0.5);

                    thisObj.sign_getUser(res.access_token);
                    // 登录成功后，重定向
                    setTimeout(function () {
                        var redirect = getQueryString('redirect');
                        if(redirect){
                            window.location.href = decodeURIComponent(redirect)
                        }else {
                            window.location.reload()
                        }
                    }, 500)
                }else{
                    layer.alert(res.error || '未知错误，请重试', {
                        title: '操作提示',
                        time: 3000,
                        btn: ['关闭'],
                        shadeClose: true,
                        icon: 2
                    })
                }
                $(data.elem).removeAttr('disabled')
            }, function () {
                $(data.elem).attr('disabled', true)
            })
        },
        // “登录/注册”模态框
        signModal: function (){
            var originUrl = $('.agreeOriginalUrl').val() || '';
            layer.open({
                type: 1,
                title: ['', 'background:#fff;border-bottom:none;height:40px;'],
                area: ['370px'],
                content: `<div class="sign-reg-modal">
                               <div class="modal-title">语聘</div> 
                               <div class="modal-txt">专注于语言服务职业机会</div> 
                               <form class="layui-form modal_sign_reg " onsubmit="return false">
                                    <div class="layui-form-item">
                                        <input type="text" name="account" class="layui-input" required lay-verify="account" placeholder="手机号/邮箱" autocomplete="off">
                                    </div>
                                    <div class="layui-form-item code">
                                        <input type="text" name="validateCode" class="layui-input min" required lay-verify="required" placeholder="验证码" autocomplete="off">
                                        <button class="layui-btn min getValidateCode" type="button" data-type="2">获取</button>
                                    </div>
                                    <div class="layui-form-item">
                                        <button class="layui-btn layui_submit sign_reg_btn" type="button" lay-submit lay-filter="sign_reg_btn">登录/注册</button>
                                    </div>
                               </form>
                               <form class="layui-form modal_sign_pwd hidden" onsubmit="return false">
                                    <div class="layui-form-item">
                                        <input type="text" name="account" class="layui-input" required lay-verify="required" placeholder="手机号/邮箱" autocomplete="off">
                                    </div>
                                    <div class="layui-form-item">
                                        <input type="password" name="password" class="layui-input min" required lay-verify="required" placeholder="密码" autocomplete="off">
                                        <i class="pwd-icon-close togglePwdEye"></i>
                                    </div>
                                    <div class="layui-form-item">
                                        <button class="layui-btn layui_submit sign_pwd_btn" type="button" lay-submit lay-filter="sign_pwd_btn">登录</button>
                                    </div>
                               </form>
                               <div class="sign-form-ag">
                                   注册即代表同意
                                   <span>[51语言<a href="${originUrl}/agreement.html" target="_blank">用户协议</a>及<a href="${originUrl}/secret.html" target="_blank">隐私协议</a>]</span>
                               </div>
                               <div class="sign-btm">
                                   <a href="javascript:;" class="modal_toggle_form">密码登录</a>
                               </div>
                         </div>`,
                success: function (){
                    var is_toggle = false;
                    $('.modal_toggle_form').click(function (){
                        is_toggle = !is_toggle;
                        $(this).html(is_toggle ? '登录/注册' : '密码登录');
                        $('.modal_sign_reg').toggleClass('hidden');
                        $('.modal_sign_pwd').toggleClass('hidden');
                    })
                }
            })
        },
        // 切换登录方式：密码登录、验证码登录
        signFormToggle: function (elem){
            var cls = elem.attr('data-cls');
            elem.addClass('active').siblings().removeClass('active');
            $('form.' + cls).removeClass('hidden').siblings('form').addClass('hidden')
        },
        // “切换城市”模态框
        changeCityModal: function (){
            var currCity = getCookie('CURRENT_CITY');
            currCity = currCity.indexOf('市') >= 0 ? currCity.slice(0, -1) : currCity;

            var { china, abroad } = locationConfig,
                firstLevel = '',
                abroadFirstLevel = '';
            //
            var selectedLocation = '';
            /*
            * 初始化地理位置，加载一级位置
            * */
            // 国内
            firstLevel = china.reduce((prev, item) => {
                return prev + `<li data-type="china"
                                       data-level="1" 
                                       data-code="${item.code}"
                                       title="${item.name}">${item.name}</li>`
            }, '');
            // 国外
            abroadFirstLevel = abroad.reduce((prev, item) => {
                return prev + `<li data-type="abroad"
                                       data-level="1" 
                                       data-code="${item.code}"
                                       title="${item.name}">${item.name}</li>`
            }, '');

            layer.open({
                type: 1,
                title: '城市/国家切换',
                area: ['610px', '365px'],
                content: `<div class="change-city-modal change_city_modal">
                             <div class="location current_location">
                                <div>当前定位：</div>
                                ${currCity && `<span class="current-city">${currCity}</span>`}
                             </div>
                             <div class="list">
                                <ul class="current_location_list">${firstLevel}</ul>
                             </div>
                             <div class="layui-form-item">
                                <button class="layui-btn current_location_btn" type="button">确定</button>
                                <button class="layui-btn layui-btn-primary" type="button" onclick="layer.closeAll()">取消</button>
                             </div>
                          </div>`,
                success: function (){
                    var $list = $('.current_location_list'),
                        $curr = $('.current_location');
                    // click事件委托
                    $('.change_city_modal')[0].onclick = function (e) {
                        var $tar = $(e.target);
                        var type = $tar.attr('data-type'),
                            level = $tar.attr('data-level'),
                            code = $tar.attr('data-code'),
                            name = $tar.attr('title');
                        var currData = [],
                            html = '';
                        // 国内
                        if(type === 'china'){
                            // 其他国家
                            if(code === 'other'){
                                $list.html(abroadFirstLevel)
                            }
                            // 省
                            if(level === '1' && code !== 'other'){
                                currData = secondLocation(china, code);
                                html = renderLocation(currData, 2, 'china');
                                $curr.append(`<span class="selected first remove" data-rm="1" data-type="china">${name}</span>`);
                                $list.html(html)
                            }
                        }
                        // 国外
                        if(type === 'abroad'){
                            // 选择国内
                            if(code === 'china'){
                                $list.html(firstLevel)
                            }
                            // 洲
                            if(level === '1' && code !== 'china'){
                                currData = secondLocation(abroad, code);
                                html = renderLocation(currData, 2, 'abroad');
                                $curr.append(`<span class="selected first remove" data-rm="1" data-type="abroad">${name}</span>`);
                                $list.html(html)
                            }
                        }
                        // 选择二级地区
                        if(level === '2'){
                            $tar.addClass('current').siblings().removeClass('current');
                            $curr.find('.second').remove();
                            $curr.append(`<span class="selected second remove" data-rm="2" data-type="china">${name}</span>`);
                            selectedLocation = name
                        }
                        // 移除选择
                        if($tar.hasClass('remove')){
                            var rm = $tar.attr('data-rm'),
                                rmType = $tar.attr('data-type');
                            // 移除二级
                            if(rm === '2'){
                                $curr.find('.second').remove();
                                $list.find('.current').removeClass('current');
                            }
                            // 移除一级
                            if(rm === '1'){
                                $curr.find('.first,.second').remove();
                                // 移除的类型
                                // china
                                if(rmType === 'china'){
                                    $list.html(firstLevel)
                                }else {
                                    $list.html(abroadFirstLevel)
                                }
                            }
                            selectedLocation = ''
                        }
                        // 确认选择
                        if($tar.hasClass('current_location_btn')){
                            if(!selectedLocation){
                                layer.msg('请选择城市/国家', {icon: 5});
                                return false
                            }
                            setCookie('CURRENT_CITY', selectedLocation, 30);
                            setTimeout(() => {
                                location.reload()
                            }, 100)
                        }
                    }
                }
            });

            // 渲染位置列表
            function renderLocation(data, level, type) {
                var html = '';
                data = data || [];
                data.forEach(item => {
                    html += `<li data-type="${type}"
                                 data-level="${level}" 
                                 data-code="${item.code}"
                                 title="${item.name}">${item.name}</li>`
                });
                return html
            }

            // 根据code，查询当前位置子级
            function secondLocation(data, code) {
                data = data || [];
                for (var i = 0, len = data.length; i<len; i++){
                    var item = data[i];
                    if(item.code === code){
                        return item.sysNations
                    }
                }
                return []
            }

        }
    };

    thisObj.init();

    // 添加 click、keyup 事件委托
    $('body').on({
        "click": function (e){
            var $tar = $(e.target);
            // 切换banner处的 登录、注册
            if($tar.hasClass('signToggle')){
                thisObj.signFormToggle($tar)
            }
            // 登录、注册 “弹框”
            if($tar.hasClass('signModal')){
                thisObj.signModal()
            }
            // 切换“隐藏/显示”密码
            if($tar.hasClass('togglePwdEye')){
                utilsLoad.togglePassword($tar)
            }
            // 密码登录
            if($tar.hasClass('sign_pwd_btn')){
                layui.form.on('submit(sign_pwd_btn)', function(data){
                    thisObj.sign_pwd({
                        account: data.field.account,
                        password: data.field.password,
                        elem: data.elem
                    })
                })
            }
            // 获取验证码
            if($tar.hasClass('getValidateCode')){
                var $account = $tar.parents('form').find('input[name="account"]'),
                    value = $account.val();
                if(!validatePhone(value) && !validateEmail(value)){
                    layer.msg('请输入正确的手机号/邮箱', {icon: 5});
                    $account.focus();
                    return false
                }
                thisObj.get_validateCode({
                    elem: $tar,
                    account: value
                })
            }
            // 验证码登录/注册
            if($tar.hasClass('sign_reg_btn')){
                layui.form.verify({
                    account: function (value, item){// 验证手机号/邮箱
                        if(!validatePhone(value) && !validateEmail(value)){
                            return '请输入正确的手机号/邮箱'
                        }
                    }
                });
                layui.form.on('submit(sign_reg_btn)', function(data){
                    thisObj.sign_code({
                        account: data.field.account,
                        password: data.field.validateCode,
                        elem: data.elem
                    })
                })
            }
            // 切换城市“模态框
            if($tar.hasClass('changeCity')){
                var { china, abroad } = locationConfig;
                if(china === null || abroad === null){
                    layer.alert('正在获取位置信息，请稍后重试', {
                        title: '提示信息',
                        btn: ['关闭'],
                        time: 3000,
                        shadeClose: true,
                        icon: 0
                    });
                    return false
                }
                if(!china.length || !abroad.length){
                    layer.alert('获取位置信息失败，请刷新页面重试', {
                        title: '提示信息',
                        btn: ['关闭'],
                        time: 3000,
                        shadeClose: true,
                        icon: 2
                    });
                    return false
                }
                thisObj.changeCityModal()
            }
        },
        "keyup": function (e){
            var $tar = $(e.target),
                $formSubmit = null;
            // Enter
            if(e.keyCode === 13){
                // 登录/注册
                $formSubmit = $tar.parents('form').find('.layui_submit');
                if(e.target.nodeName === 'INPUT' && $formSubmit.length){
                    $formSubmit.click()
                }
            }
        }
    })

})(jQuery, window, document);
